<?php

namespace App\Admin\Controllers;

use App\Models\MembershipCode;
use Dcat\Admin\Controllers\AdminController;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Layout\Content;
use Illuminate\Http\Request;
use Carbon\Carbon;

class MembershipCodeController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(MembershipCode::with('user'), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('code', '兑换码')->copyable();
            $grid->column('type', '类型')->display(function ($type) {
                $types = [
                    'day' => '日卡',
                    'month' => '月卡',
                    'year' => '年卡',
                    'permanent' => '永久卡'
                ];
                $colors = [
                    'day' => 'primary',
                    'month' => 'warning',
                    'year' => 'success',
                    'permanent' => 'dark'
                ];
                return "<span class='badge badge-{$colors[$type]}'>{$types[$type]}</span>";
            });
            $grid->column('duration', '时长')->display(function ($duration) {
                return $duration ? $duration . '天' : '永久';
            });
            $grid->column('is_used', '状态')->display(function ($isUsed) {
                return $isUsed ? 
                    "<span class='badge badge-success'>已使用</span>" : 
                    "<span class='badge badge-secondary'>未使用</span>";
            });
            $grid->column('user.name', '使用者');
            $grid->column('used_at', '使用时间');
            $grid->column('expires_at', '过期时间');
            $grid->column('created_at', '创建时间')->sortable();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('type', '类型')->select([
                    'day' => '日卡',
                    'month' => '月卡',
                    'year' => '年卡',
                    'permanent' => '永久卡'
                ]);
                $filter->equal('is_used', '状态')->select([
                    0 => '未使用',
                    1 => '已使用'
                ]);
                $filter->like('code', '兑换码');
                $filter->between('created_at', '创建时间')->datetime();
            });

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                if ($this->is_used) {
                    $actions->disableDelete();
                    $actions->disableEdit();
                }
            });

            $grid->batchActions(function (Grid\Tools\BatchActions $batch) {
                $batch->add('批量生成', new BatchGenerateAction());
            });

            $grid->tools(function (Grid\Tools $tools) {
                $tools->append('<a href="' . admin_route('membership-codes.generate') . '" class="btn btn-primary"><i class="fa fa-plus"></i> 批量生成兑换码</a>');
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, MembershipCode::with('user'), function (Show $show) {
            $show->field('id');
            $show->field('code', '兑换码');
            $show->field('type', '类型')->as(function ($type) {
                $types = [
                    'day' => '日卡',
                    'month' => '月卡',
                    'year' => '年卡',
                    'permanent' => '永久卡'
                ];
                return $types[$type] ?? $type;
            });
            $show->field('duration', '时长')->as(function ($duration) {
                return $duration ? $duration . '天' : '永久';
            });
            $show->field('is_used', '状态')->as(function ($isUsed) {
                return $isUsed ? '已使用' : '未使用';
            });
            $show->field('user.name', '使用者');
            $show->field('used_at', '使用时间');
            $show->field('expires_at', '过期时间');
            $show->field('created_at', '创建时间');
            $show->field('updated_at', '更新时间');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(MembershipCode::class, function (Form $form) {
            $form->display('id');
            $form->text('code', '兑换码')->required()->rules('unique:membership_codes,code,' . $form->getKey());
            $form->select('type', '类型')->options([
                'day' => '日卡',
                'month' => '月卡',
                'year' => '年卡',
                'permanent' => '永久卡'
            ])->required();
            $form->number('duration', '时长（天）')->help('永久卡请留空');
            $form->datetime('expires_at', '兑换码过期时间')->help('兑换码本身的过期时间，不是会员到期时间');

            $form->saving(function (Form $form) {
                if ($form->type === 'permanent') {
                    $form->duration = null;
                } elseif (!$form->duration) {
                    $durations = [
                        'day' => 1,
                        'month' => 30,
                        'year' => 365
                    ];
                    $form->duration = $durations[$form->type] ?? 1;
                }
            });
        });
    }

    /**
     * 批量生成兑换码页面
     */
    public function generate(Content $content)
    {
        return $content
            ->title('批量生成兑换码')
            ->body(view('admin.membership-codes.generate'));
    }

    /**
     * 处理批量生成兑换码
     */
    public function doGenerate(Request $request)
    {
        $request->validate([
            'type' => 'required|in:day,month,year,permanent',
            'count' => 'required|integer|min:1|max:100',
            'expires_at' => 'nullable|date|after:now'
        ]);

        $codes = [];
        for ($i = 0; $i < $request->count; $i++) {
            $code = MembershipCode::generateCode(
                $request->type,
                $request->expires_at ? Carbon::parse($request->expires_at) : null
            );
            $codes[] = $code;
        }

        return response()->json([
            'status' => true,
            'message' => "成功生成 {$request->count} 个兑换码",
            'data' => $codes->pluck('code')
        ]);
    }
}